﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 筛选图号批次
{
    public partial class Form1 : Form
    {
        DataSet ds = new DataSet();
        public Form1()
        {
            InitializeComponent();
        }
        void Import(string path)
        {
            if (!File.Exists(path))
            {
                MessageBox.Show($"路径{path}不存在");
            }
            if(Path.GetExtension(path).ToUpper()!= ".XLSX")
            {
                MessageBox.Show($"文件不为XLSX");
                return;
            }
            ds.Tables.Clear();
            var sheets = MiniExcelLibs.MiniExcel.GetSheetNames(path);
            foreach (var sheetName in sheets)
            {
                var dt = MiniExcelLibs.MiniExcel.QueryAsDataTable(path, sheetName: sheetName, excelType: MiniExcelLibs.ExcelType.XLSX);
                ds.Tables.Add(dt);
                AddDgv(dt);
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            var dia = openFileDialog1.ShowDialog();
            if(dia == DialogResult.OK)
            {
                try
                {
                    tabControl1.TabPages.Clear();
                    Import(openFileDialog1.FileName);
                    Comparer();
                }
                catch (Exception ex)
                {

                    MessageBox.Show("导入失败:"+ex.Message);
                }

            }
        }
        void AddDgv(DataTable dt)
        {
            tabControl1.TabPages.Add(dt.TableName);
            var tabPage = tabControl1.TabPages[tabControl1.TabCount - 1];
            var dgv = new DataGridView();
            dgv.Dock = DockStyle.Fill;
            dgv.DataSource = dt;
            dgv.AllowUserToAddRows = false;
            dgv.AllowUserToDeleteRows = false;
            dgv.AllowUserToOrderColumns = false;    
            tabPage.Controls.Add(dgv);
            foreach (DataGridViewColumn col in dgv.Columns)
            {
                col.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            }
        }

        private void Comparer()
        {
            var dt0 = ds.Tables[0];
            var dt1 = ds.Tables[1];

            if(!dt0.Columns.Contains("图号") || !dt0.Columns.Contains("批号")|| !dt0.Columns.Contains("数量"))
            {
                MessageBox.Show($"[{dt0.TableName}]不包含列图号、批号、数量");
                return;
            }
            if (!dt1.Columns.Contains("图号") || !dt1.Columns.Contains("批号") || !dt1.Columns.Contains("数量"))
            {
                MessageBox.Show($"[{dt0.TableName}]不包含列图号、批号或数量");
                return;
            }
            var hashSet = new HashSet<string>();
            foreach (DataRow row in dt0.Rows)
            {
                hashSet.Add(row["图号"].ToString());
            }
            foreach (DataRow row in dt1.Rows)
            {
                hashSet.Add(row["图号"].ToString());
            }
            foreach (var str in hashSet)
            {
                var rows0 = dt0.Select($"图号='{str}'");
                var rows1 = dt1.Select($"图号='{str}'");
                var dt = new DataTable(str);
                dt.Columns.Add(dt0.TableName + " 图号");
                dt.Columns.Add(dt0.TableName + " 批号");
                dt.Columns.Add(dt0.TableName + " 数量");
                dt.Columns.Add("   ");
                dt.Columns.Add(dt1.TableName + " 图号");
                dt.Columns.Add(dt1.TableName + " 批号");
                dt.Columns.Add(dt1.TableName + " 数量");
                dt.Columns.Add("  ");
                dt.Columns.Add("是否匹配");

                dt.Columns[2].DataType = typeof(double);
                dt.Columns[2].DefaultValue = 0;

                dt.Columns[6].DataType = typeof(double);
                dt.Columns[6].DefaultValue = 0;


                HashSet<string> isUse = new HashSet<string>();
                foreach (var row in rows0)
                {
                    var batch = row["批号"].ToString();

                    if (isUse.Contains(batch))
                        continue;
                    var newRow = dt.Rows.Add();
                    newRow[0] = str;
                    newRow[1] = batch;
                    newRow[2] = 0;
                    var findRows0 = dt0.Select($"图号='{str}' and 批号='{batch}'");
                    double qty0 = 0;
                    foreach (var item in findRows0)
                    {
                        var str0 = item[2]?.ToString();
                        if (!string.IsNullOrEmpty(str0))
                        {
                            double temp;
                            double.TryParse(str0, out temp);
                            qty0 += temp;
                        }
                    }
                    newRow[2] = qty0;

                    var findRows1 = dt1.Select($"图号='{str}' and 批号='{batch}'");                
                    if(findRows1.Length > 0)
                    {
                        newRow[4] = str;
                        newRow[5] = findRows1[0]["批号"];
                        newRow[6] = 0;
                        double qty1 = 0;
                        foreach (var item in findRows1)
                        {
                            var str0 = item[2]?.ToString();
                            if (!string.IsNullOrEmpty(str0))
                            {
                                double temp;
                                double.TryParse(str0, out temp);
                                qty1 += temp;
                            }
                            newRow[6] = qty1;

                        }
                    }
                    isUse.Add(batch.ToUpper());
                }
                foreach (var row in rows1)
                {

                    var batch = row["批号"].ToString();
                    if (isUse.Contains(batch.ToUpper()))
                        continue;
                    var findRows1 = dt1.Select($"图号='{str}' and 批号='{batch}'");
                    var newRow = dt.Rows.Add();

                    if (findRows1.Length > 0)
                    {
                        newRow[4] = str;
                        newRow[5] = findRows1[0]["批号"];
                        newRow[6] = 0;
                        double qty1 = 0;
                        foreach (var item in findRows1)
                        {
                            var str0 = row[2]?.ToString();
                            if (!string.IsNullOrEmpty(str0))
                            {
                                double temp;
                                double.TryParse(str0, out temp);
                                qty1 += temp;
                            }
                            newRow[6] = qty1;

                        }
                    }

                    isUse.Add(batch.ToUpper());


                }
                var summaryRow = dt.Rows.Add();
                double sum1 = 0,sum2 = 0;
                foreach (DataRow row in dt.Rows)
                {
                    var str0 = row[2]?.ToString();
                    if (!string.IsNullOrEmpty(str0))
                    {
                        double temp;
                        double.TryParse(str0, out temp);
                        sum1 += temp;
                    }
                    var str1 = row[6]?.ToString();
                    if (!string.IsNullOrEmpty(str1))
                    {
                        double temp;
                        double.TryParse(str1, out temp);
                        sum2 += temp;
                    }
                    row[8] = (str0 == str1 ? "是" : "否");
                }
                summaryRow[2] = sum1;
                summaryRow[6] = sum2;
                
                ds.Tables.Add(dt);
                AddDgv(dt);
            }
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            var dia = saveFileDialog1.ShowDialog();
            if(dia == DialogResult.OK)
            {
                try
                {
                    if (File.Exists(saveFileDialog1.FileName))
                        File.Delete(saveFileDialog1.FileName);

                    MiniExcelLibs.MiniExcel.SaveAs(saveFileDialog1.FileName, ds);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("导出失败："+ex.Message);

                }


            }
        }
    }
}
